/**
 * 
 */
package com.pulsarwebdevelopment.concordance;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

/**
 * @author Matthew Dickinson
 * Allows for writing of word to verse(s) pairs without having to embed that logic in your programs
 * Created: 3/14/2011 (Pi Day!)
 *
 */
public class ConcordanceOutputStream<K, V> extends ConcordanceOutput<K, V> {

	public static enum ListStyle{
		ONE_PER_LINE,
		ONE_PER_LINE_TRUNCATED,
		SINGLE_LINE,
		SINGLE_LINE_TRUNCATED;
	}

	private ListStyle outputType;
	private PrintWriter printer;
	private Writer backingWriter;

	public ConcordanceOutputStream(Writer baseWriter, ListStyle chosenOuput) {
		this.backingWriter = baseWriter;
		this.printer = new PrintWriter(baseWriter);
		this.outputType = chosenOuput;
	}

	/* (non-Javadoc)
	 * @see concordance.ConcordanceOuput#flush()
	 */
	@Override
	public void flush(){
		switch(outputType){
			case ONE_PER_LINE:
			case ONE_PER_LINE_TRUNCATED:
				if(curValues.size() > 0){
					printer.format("%-30s %30s\n", curKey.toString(), curValues.get(0).toString());
	
					for(int i = 1; i < curValues.size(); i++){
						printer.format("%-30s %30s\n", "", curValues.get(i).toString());
					}
				}
				break;
			case SINGLE_LINE:	
			case SINGLE_LINE_TRUNCATED:
				if(curValues.size() > 0){
					printer.format("%-30s", curKey);
					
					//check whether the verse list is within the allowable size
					if(curValues.size() <= Concordance.getDisplayLength()){
						for(int i = 0; i < curValues.size(); i++){
							printer.append(" " + curValues.get(i).toString());
							if(i != curValues.size() -1){
								printer.append(", "); //append comman on everything by last row
							}
						}
					}else{
						printer.append("(");
						printer.append(Integer.toString(curValues.size()));
						printer.append(")");
					}
					printer.append("\n\n");
					break;
				}
		}
	}

	/**
	 * Get the backing writer for this ConcordanceOutputStream
	 * @return backing writer
	 */
	public Writer getWriter(){
		return backingWriter;
	}

	/** 
	 * Close this output stream. This will also close the underlying printer and output streams. 
	 */
	public void close(){
		this.printer.close();

		if(backingWriter != null){
			try{
				backingWriter.close();
			}catch(IOException e){
				System.err.println("unable to close writer");
			}
		}
	}
}
